<script setup lang="tsx">
import { useTimeAgo } from '@/hooks/web/useTimeAgo'
import { ElRow, ElCol, ElSkeleton, ElCard, ElDivider, ElLink, ElDialog } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { ref, reactive } from 'vue'
import { CountTo } from '@/components/CountTo'
import PanelGroup from './components/PanelGroup.vue'
// import { Echart } from '@/components/Echart'
import { EChartsOption } from 'echarts'
import { radarOption } from './echarts-data'
import PDFViewer from './components/PDFViewer.vue'
import {
  getTeamApi
} from '@/api/dashboard/workplace'
import type { Team } from '@/api/dashboard/workplace/types'
import { set } from 'lodash-es'
import { computed } from 'vue'
import { reqAllFile } from '@/api/dashboard/statistic'
import { BasicStatistic, FileInfo, AllFilesResponseData } from '@/api/dashboard/statistic/type'
import { reqClassificationTree } from '@/api/classify'
//引入获取任务的请求的方法
import { reqAllMission, reqDepartmentMission } from '@/api/bianmafuma'
import { StatisticObj, statisticClassifications } from './api/index'
import { unref } from 'vue'
// import { departmentMap } from '../../../public/department'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
import { inject } from 'vue'

const  departmentMap  = inject<any>('departmentMap')

const $router = useRouter()

const loading = ref(true)

const userStore = useUserStore()

const getName = computed(() => {
  const name = userStore.getUserInfo?.username || 'admin'

  if (name != 'admin') {
    return departmentMap[name] + '工作人员'
  }
  return '管理员'
})

/*  第一行，登录问候和基础数据统计 */
const greeting = computed(() => {
  const date = new Date().getHours()

  if (6 < date && date < 11)
    return '早上好，'
  else if (11 <= date && date <= 14)
    return '中午好，'
  else if (14 < date && date < 17)
    return '下午好，'
  else if (17 <= date && date <= 19)
    return '傍晚好，'
  else
    return '夜深了，'
})

const wish = computed(() => {
  const date = new Date().getHours()

  if (6 < date && date < 15)
    return '祝你今天工作顺利。'
  else if (15 <= date && date <= 19)
    return '感谢你今天的辛勤付出。'
  else
    return '还在工作的你请多注意身体。'
})

const novel = computed(() => {
  const date = new Date().getHours()

  if (6 < date && date < 11)
    return '——一日之计在于晨'
  else if (11 <= date && date <= 19)
    return '——天行健，君子以自强不息'
  else
    return '——长风破浪会有时，直挂云帆济沧海'
})


// 基础数据统计的管理对象
const basicStatisitcObj = reactive<BasicStatistic[]>([{
  label: '系统总编码赋码条数',
  count: 37185
}, {
  label: '相关责任部门数',
  count: 18
}])

const classifyTypeStatistics = ref<StatisticObj[]>([])

const radarOptionData = reactive<EChartsOption>(radarOption) as EChartsOption
// 实体分类大中小类具体统计信息
const getClassifyTypeStatistic = () => {
  reqClassificationTree().then(res => {
    const data = res.data
    const promise = statisticClassifications(data, '黄冈', '武穴')
    promise.then((res => {
      classifyTypeStatistics.value = res

      const indicatorMap = new Map<string, number>()

      for (const item of unref(classifyTypeStatistics)) {
        for (const indicator of item.value) {
          if (indicatorMap.has(indicator.typeName)) {
            const value = Math.max(indicatorMap.get(indicator.typeName)!, indicator.count)
            indicatorMap.set(indicator.typeName, value)
          } else {
            indicatorMap.set(indicator.typeName, indicator.count)
          }
        }
      }

      const indicators: any[] = []
      indicatorMap.forEach((value, key) => {
        indicators.push({
          name: key,
          max: value + Math.floor(value * Math.random())
        })
      })
      set(radarOptionData,
        'legend.data',
        unref(classifyTypeStatistics).map((item: any) => item.name)
      )

      set(
        radarOptionData,
        'radar.indicator',
        indicators
      )

      set(
        radarOptionData,
        'series',
        {
          name: '武穴市大中小类覆盖指数',
          type: 'radar',
          data: [
            ...unref(classifyTypeStatistics).map(item => ({
              name: item.name,
              value: item.value.map(item => item.count)
            }))
          ]
        }
      )
    }))
  })
}

// 统计近期编码赋码情况
const codingData = reactive<any[]>([])

const getCodingInfos = async () => {
  let res
  if (userStore.userInfo?.role === 'admin')
    res = await reqAllMission(1, 8)
  else
    res = await reqDepartmentMission(userStore.userInfo!.username, 1, 8)
  Object.assign(codingData, res.data.list.map((item: any) => ({
    department: item.taskDepartment,
    dataNum: item.dataNum,
    taskStatus: taskState(item.taskStatus),
    applyTime: item.applyTime,
    id: item.id
  })))
}

const timeFormat = (date: Date) => {
  return date.getFullYear() + '年' + (date.getMonth() + 1) + '月' + date.getDate() + '日'
}

const taskState = (state: number) => {
  switch (state) {
    case 0:
      return {
        text: '进行中',
        type: 'primary'
      }
    case 1:
      return {
        text: '已完成',
        type: 'success'
      }
    case 2:
      return {
        text: '错误',
        type: 'danger'
      }
    default:
      return {
        text: '进行中',
        type: 'primary'
      }
  }
}

const goDetail = (id: string) => {
  $router.push({
    path: '/encoding/application-detail',
    query: {
      id: id
    }
  })
}

// 快捷操作

const menu = [{
  label: '编码申请',
  icon: 'fa:upload',
  onClick: () => {
    $router.push({
      path: '/encoding/encoding-application'
    })
  }
}, {
  label: '编码管理',
  icon: 'ic:baseline-manage-search',
  onClick: () => {
    $router.push({
      path: '/encoding/encoding-result'
    })
  }
}, {
  label: '实体分类',
  icon: 'mingcute:classify-add-2-line',
  onClick: () => {
    $router.push({
      path: '/classify/management'
    })
  }
},
{
  label: '武穴市编码工具',
  icon: 'entypo:tools',
  onClick: () => {
    $router.push({
      path: '/toolbox/index'
    })
  }
},
]

// 获取团队
let team = reactive<Team[]>([])

const getTeam = async () => {
  const res = await getTeamApi().catch(() => { })
  if (res) {
    team = Object.assign(team, res.data)
  }
}

const fileInfos = ref<FileInfo[]>([])
const getFileInfos = async () => {
  const res: AllFilesResponseData = await reqAllFile()
  for (let i = 0; i < res.data.length; i++)
    fileInfos.value.push(res.data[i])
}

const dialogVisible = ref(false)
const pdfUrl = ref('')

const getPDF = async (id: string) => {
  // const res: Blob = await downloadResult(id)
  // pdfUrl.value = URL.createObjectURL(new Blob([res], { type: `application/pdf` }))
  pdfUrl.value = 'http://58.48.30.30:17091/data/' + id + '.pdf'
}

const previewPDF = async (id: string) => {
  pdfUrl.value = ''
  dialogVisible.value = true
  await getPDF(id)
}


const onLoaded = (pdfApp: any) => {
  console.log('loaded app:', pdfApp)
}

const downloadPDF = async (name: string, id: string) => {
  // await getPDF(id)
  const url = 'http://58.48.30.30:17091/data/' + id + '.pdf'
  const a = document.createElement('a')
  a.style.display = 'none'
  a.href = url
  a.download = name + '.pdf'
  const event = new MouseEvent('click')
  a.dispatchEvent(event)
}

const getAllApi = async () => {
  await Promise.all([getClassifyTypeStatistic(), getFileInfos(), getTeam(), getCodingInfos()])
  loading.value = false
}

getAllApi()
const { t } = useI18n()
</script>

<template>
  <div>
    <ElCard shadow="never">
      <ElSkeleton :loading="loading" animated>
        <ElRow :gutter="20" justify="space-between">
          <ElCol :xl="16" :lg="16" :md="16" :sm="24" :xs="24">
            <div class="flex items-center">
              <img src="@/assets/imgs/employee.png" alt="" class="w-70px h-70px rounded-[50%] mr-20px" />
              <div>
                <div class="text-20px">
                  {{ greeting }}<b>{{ getName }}</b>，{{ wish }}
                </div>
                <div class="mt-10px text-14px text-gray-500">
                  {{ novel }}
                </div>
              </div>
            </div>
          </ElCol>
          <ElCol :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
            <div class="flex h-70px items-center justify-end lt-sm:mt-20px">
              <template v-for="(item, index) in basicStatisitcObj" :key="index">
                <div class="px-8px text-right">
                  <div class="text-14px text-gray-400 mb-20px">{{ item.label }}</div>
                  <CountTo class="text-20px" :start-val="0" :end-val="item.count" :duration="2600" />
                </div>
                <ElDivider v-if="index != basicStatisitcObj.length - 1" direction="vertical" />
              </template>
            </div>
          </ElCol>
        </ElRow>
      </ElSkeleton>
    </ElCard>
  </div>

  <ElRow class="mt-20px" :gutter="20" justify="space-between">
    <ElCol :xl="16" :lg="16" :md="24" :sm="24" :xs="24" class="mb-20px">
      <ElCard shadow="never">
        <template #header>
          <div class="flex justify-between">
            <span>武穴市实体分类对比</span>
            <!-- <ElLink type="primary" :underline="false">{{ t('workplace.more') }}</ElLink> -->
          </div>
        </template>
        <ElSkeleton :loading="loading" animated>
          <ElRow align="middle">
            <ElCol :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
              <ElRow>
                <ElCol :span="24">
                  <!-- <ElCard shadow="hover"> -->
                  <template v-for="item in classifyTypeStatistics">
                    <!-- <div style="display:flex; justify-content: space-around;align-items: center"> -->
                    <!-- <div class="flex items-center">
                          <ElAvatar :size="70" style="font-size: 20px; 
                          background-color: var(--el-color-primary);">
                            {{ item.name }}
                          </ElAvatar>
                        </div> -->
                    <!-- <div v-for="i in item.value" style="font-size: 18px;"
                          :style="index % 2 != 0 ? 'color:var(--el-color-primary);' : 'color:var(--el-color-danger);'">
                          <span> {{ i.typeName }}</span>
                          <CountTo style="padding: 0 5px;font-size: 24px;" :start-val="0" :end-val="i.count"
                            :duration="2000" />
                          <span>个</span>
                        </div> -->
                    <PanelGroup :city="item.name" :count="item.value" :color="item.color" />
                    <!-- </div> -->
                    <!-- <div class="mt-20px text-14px text-gray-400 flex justify-between">
                        <span>大中小类覆盖情况</span>
                        <span>截至{{ formatTime(new Date(), 'yyyy-MM-dd') }}</span>
                      </div> -->
                  </template>
                  <!-- </ElCard> -->
                </ElCol>
              </ElRow>

            </ElCol>
            <!-- <ElCol :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
              <Echart :options="radarOptionData" :height="300" />
            </ElCol> -->
          </ElRow>
        </ElSkeleton>
      </ElCard>

      <ElCard shadow="never" class="mt-20px">
        <template #header>
          <div class="flex justify-between">
            <span>近期发布的规范及标准文件</span>
            <!-- <ElLink type="primary" :underline="false">{{ t('workplace.more') }}</ElLink> -->
          </div>
        </template>
        <ElSkeleton :loading="loading" animated>
          <div v-for="(item, index) in fileInfos" :key="`file-${index}`">
            <div class="flex items-center">
              <img src="@/assets/imgs/PDF.png" alt="" class="w-35px h-35px rounded-[50%] mr-20px" />
              <div>
                <div class="text-16px">
                  《 {{ item.filename }}》
                </div>
                <div class="mt-15px text-14px text-gray-400">
                  <span style="color: var(--el-color-primary);"> {{ item.uploadUser }}</span>
                  发布于 {{ useTimeAgo(item.uploadTime) }}
                </div>
              </div>
              <div class="ml-auto">
                <ElLink type="primary" style="font-size: 14px;" @click="previewPDF(item.fileId.toString())">预览 </ElLink>
                <ElLink type="primary" style="font-size: 14px;margin-left: 10px;"
                  @click="downloadPDF(item.filename, item.fileId.toString())">下载 </ElLink>
              </div>
            </div>
            <ElDivider />
          </div>

        </ElSkeleton>
      </ElCard>
    </ElCol>

    <ElCol :xl="8" :lg="8" :md="24" :sm="24" :xs="24" class="mb-20px">
      <ElCard shadow="never">
        <template #header>
          <span>近期编码赋码情况</span>
        </template>
        <ElSkeleton :loading="loading" animated>
          <ul style="margin:0;padding-left: 20px;">
            <li v-for="(item, index) in codingData" :key="`coding-${index}`">
              <ElRow style="align-items: center;">
                <ElCol :span="18">
                  <div class="text-14px text-gray-400">
                    <b>{{ departmentMap[item.department] }}</b>于{{ timeFormat(new Date(item.applyTime)) }}完成{{
        item.dataNum }}条数据编码赋码。
                  </div>
                </ElCol>
                <ElCol :span="6">
                  <ElLink type="primary" style="float: right" @click="goDetail(item.id)">查看详情>></ElLink>
                </ElCol>
              </ElRow>

              <ElDivider v-if="index !== codingData.length - 1" style="margin: 12px 0;" />
            </li>
          </ul>
        </ElSkeleton>
      </ElCard>

      <ElCard shadow="never" class="mt-20px">
        <template #header>
          <span>{{ t('workplace.shortcutOperation') }}</span>
        </template>
        <ElSkeleton :loading="loading" animated>
          <ElRow :gutter="50">
            <ElCol v-for="item, index in menu" :key="`card-${index}`" :xl="12" :lg="12" :md="12" :sm="24" :xs="24"
              class="mb-10px">
              <ElLink style="margin: 0 10px;" type="default" :underline="false" @click="item.onClick()">
                <Icon :icon="item.icon" style="margin-right: 5px;" /> <span class="text-size-16px">{{ item.label
                  }}</span>
              </ElLink>
            </ElCol>
          </ElRow>
        </ElSkeleton>
      </ElCard>

      <!-- <ElCard shadow="never" class="mt-20px">
        <template #header>
          <span>{{ t('workplace.team') }}</span>
        </template>
        <ElSkeleton :loading="loading" animated>
          <ElRow>
            <ElCol v-for="item in team" :key="`team-${item.name}`" :span="12" class="mb-20px">
              <div class="flex items-center">
                <Icon :icon="item.icon" class="mr-10px" />
                <ElLink type="default" :underline="false">
                  {{ item.name }}
                </ElLink>
              </div>
            </ElCol>
          </ElRow>
        </ElSkeleton>
      </ElCard> -->
    </ElCol>
  </ElRow>
  <ElDialog v-model="dialogVisible" title="文件预览" width="900" align-center>
    <div style="display: flex;justify-content: center;">
      <PDFViewer page-scale="page-fit" :width="850" :height="700" theme="dark" :src="pdfUrl" @loaded="onLoaded" />
    </div>
    <!-- <div style="display: flex;justify-content: center;">
      <iframe  style="width: 850px;height: 700px"  :src="pdfUrl"  />
    </div> -->
  </ElDialog>
</template>
